from hashlib import md5

import tos
from feapder.utils.log import log
try:
    from utils.utils import send_feishu_message
except ImportError:
    from utils import send_feishu_message

# 从环境变量获取 AK 和 SK 信息。
ak = 'AKLTMzM5ZGFjYzg0ZTdkNDdkYmIwZjU2NmM4ZmY5OTk2NzM'
sk = 'TlRCa1l6WmtObVEyTmpVMk5EbGxNV0prTldJMk1ERXlOMlZoWldJeE1tRQ=='
# your endpoint 和 your region 填写Bucket 所在区域对应的Endpoint。# 以华北2(北京)为例，your endpoint 填写 tos-cn-beijing.volces.com，your region 填写 cn-beijing。
endpoint = "tos-cn-beijing.volces.com"
region = "cn-beijing"
bucket = "playlet-crm"
tos_path = 'fanqie_ip'

# 创建TosClientV2对象
client = tos.TosClientV2(ak, sk, endpoint, region)


def upload(file_bytes: bytes, file_type: str = 'mp4'):
    file_name = md5(file_bytes).hexdigest() + f'.{file_type}'
    for _ in range(5):
        try:
            # 调用接口请求TOS服务，例如上传对象
            resp = client.put_object(bucket, f"{tos_path}/{file_name}", content=file_bytes)
            log.info(f"上传成功: {file_name}，request id： {resp.request_id}")
            return f'https://{bucket}.{endpoint}/{tos_path}/{file_name}'
        except tos.exceptions.TosClientError as e:
            # 操作失败，捕获客户端异常，一般情况为非法请求参数或网络异常
            log.warning(f"上传失败: {file_name}，message: {e.message}，cause: {e.cause}")
        except tos.exceptions.TosServerError as e:
            # 操作失败，捕获服务端异常，可从返回信息中获取详细错误信息
            log.warning(f"上传失败: {file_name}，code: {e.code}，request id: {e.request_id}，message: {e.message}，"
                        f"http code: {e.status_code}，ec: {e.ec}，request url: {e.request_url}")
        except Exception as e:
            log.warning(f"上传失败: {file_name}，error: {e}")
    else:
        send_feishu_message( message=f"文件：{file_name}，已达到最大重试次数")
        return None


if __name__ == '__main__':
    import requests

    resposne = requests.get('http://p3-novel-sign.byteimg.com/novel-pic/fcebaa9adab888056c065218c8411ba6~tplv-noop.image?lk3s=751eef77&x-expires=1751626365&x-signature=AYiyis%2BWTDcqCjHincT4gn4pL0o%3D')
    print(upload(resposne.content,'jpg'))
